import React, { useEffect, useState } from 'react';
import Sidebar from '../components/Sidebar';
import AccountInfoModal from '../components/AccountInfoModal';
import AccountSelectorModal from '../components/AccountSelectorModal';
import ChatList from '../components/ChatList';
import ChatDetail from '../components/ChatDetail';
import ContactList from '../components/ContactList';
import SettingsPanel from '../components/SettingsPanel';
import { getAllAccounts, getSessionList, getSessionMessages, exportAccountData, getContactList, openFileOrExplorer, openDirectoryDialog, openLogFileExplorer, getAppVersion } from '../api/wechat';
import { safeCall } from '../api/safeCall';
import type { AccountInfo, Session, Message, Contact } from '../types/wechat';

const MainPage: React.FC = () => {
  const [accounts, setAccounts] = useState<AccountInfo[]>([]);
  const [currentAccountId, setCurrentAccountId] = useState<string>('');
  const [showAccountModal, setShowAccountModal] = useState(false);
  const [showSelector, setShowSelector] = useState(false);
  const [sessions, setSessions] = useState<Session[]>([]);
  const [selectedSessionId, setSelectedSessionId] = useState<string | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [sidebar, setSidebar] = useState('chat');
  const [contacts, setContacts] = useState<Contact[]>([]);

  useEffect(() => {
    safeCall(getAllAccounts(), '获取账号列表失败').then(accs => {
      if (!accs) return;
      setAccounts(accs);
      if (accs.length > 0) setCurrentAccountId(accs[0].id);
    });
  }, []);

  useEffect(() => {
    if (currentAccountId) {
      safeCall(getSessionList(currentAccountId), '获取会话列表失败').then(sessions => {
        if (!sessions) return;
        setSessions(sessions);
        if (sessions.length > 0) {
          setSelectedSessionId(sessions[0].id);
        } else {
          setSelectedSessionId(null);
        }
      });
      safeCall(getContactList(currentAccountId), '获取联系人失败').then(contacts => {
        if (!contacts) return;
        setContacts(contacts);
      });
    }
  }, [currentAccountId]);

  useEffect(() => {
    if (selectedSessionId) {
      safeCall(getSessionMessages(selectedSessionId), '获取聊天记录失败').then(msgs => {
        if (!msgs) return;
        setMessages(msgs);
      });
    }
  }, [selectedSessionId]);

  const currentAccount = accounts.find(a => a.id === currentAccountId);

  const renderContent = () => {
    if (sidebar === 'chat') {
      return (
        <>
          <ChatList
            sessions={sessions}
            selectedId={selectedSessionId}
            onSelect={setSelectedSessionId}
            onSearch={() => {}}
          />
          {selectedSessionId && (
            <ChatDetail
              messages={messages}
              sessionName={sessions.find(s => s.id === selectedSessionId)?.name || ''}
            />
          )}
        </>
      );
    }
    if (sidebar === 'contacts') {
      return (
        <div style={{ padding: 0, width: '100%' }}>
          <ContactList contacts={contacts} onSelect={() => {}} />
        </div>
      );
    }
    if (sidebar === 'settings') {
      return (
        <div style={{ padding: 0, width: '100%' }}>
          <SettingsPanel
            account={currentAccount}
            onExport={() => {
              if (currentAccount) safeCall(exportAccountData(currentAccount.id), '导出失败').then(res => {
                if (res) alert(res.message);
              });
            }}
            onOpenWeChatPath={() => currentAccount && safeCall(openPath(currentAccount.wechatPath), '打开路径失败')}
            onOpenExportPath={() => currentAccount && safeCall(openPath(currentAccount.exportPath), '打开路径失败')}
            onChangeExportPath={() => currentAccount && safeCall(changeExportPath(currentAccount.id), '修改导出路径失败')}
            onCheckUpdate={() => safeCall(checkUpdate(), '检查更新失败')}
            onShowLog={() => safeCall(showLog(), '打开日志失败')}
          />
        </div>
      );
    }
    if (sidebar === 'info') {
      return (
        <div style={{ padding: 24 }}>
          <h2>关于</h2>
          <p>wechatDataBackup 桌面版</p>
          <p>前端由 React + Vite 还原</p>
        </div>
      );
    }
    return null;
  };

  // 使用封装的 API 函数
  const openPath = async (path: string) => {
    console.log('尝试打开路径:', path);
    try {
      const result = await openFileOrExplorer(path, true);
      console.log('后端返回结果:', result);
      // 解析后端返回的JSON结果
      if (typeof result === 'string') {
        try {
          const parsed = JSON.parse(result);
          if (parsed.status === 'failed') {
            alert(`打开路径失败: ${parsed.result}`);
          } else {
            console.log(`成功打开路径: ${parsed.result}`);
            // 成功时也可以显示一个简短的提示
            // alert('路径已打开');
          }
        } catch {
          // 如果不是JSON格式，直接显示结果
          console.log('打开路径结果:', result);
        }
      }
    } catch (error) {
      console.error('打开路径出错:', error);
      alert('打开路径失败');
    }
  };
  const changeExportPath = async (_accountId: string) => {
    console.log('=== changeExportPath START ===');
    console.log('Account ID:', _accountId);
    
    try {
      console.log('Calling openDirectoryDialog...');
      const startTime = Date.now();
      
      const path = await openDirectoryDialog();
      const endTime = Date.now();
      
      console.log(`openDirectoryDialog completed in ${endTime - startTime}ms`);
      console.log('Returned path:', path);
      
      if (path) {
        console.log('Path selected successfully:', path);
        alert(`已选择导出路径：${path}`);
      } else {
        console.log('No path selected (user cancelled or error)');
      }
    } catch (error) {
      console.error('Error in changeExportPath:', error);
      alert('选择路径失败');
    }
    
    console.log('=== changeExportPath END ===');
  };
  const checkUpdate = async () => {
    try {
      const version = await getAppVersion();
      alert(`当前版本：${version}`);
    } catch {
      alert('获取版本信息失败');
    }
  };
  const showLog = async () => {
    try {
      await openLogFileExplorer();
    } catch {
      alert('打开日志失败');
    }
  };

  // 切换 sidebar 时自动刷新数据
  const handleSidebarSelect = (key: string) => {
    setSidebar(key);
    if (key === 'contacts' && currentAccountId) {
      safeCall(getContactList(currentAccountId), '获取联系人失败').then(contacts => {
        if (!contacts) return;
        setContacts(contacts);
      });
    }
    if (key === 'chat' && currentAccountId) {
      safeCall(getSessionList(currentAccountId), '获取会话列表失败').then(sessions => {
        if (!sessions) return;
        setSessions(sessions);
        if (sessions.length > 0) {
          setSelectedSessionId(sessions[0].id);
        } else {
          setSelectedSessionId(null);
        }
      });
    }
    if (key === 'settings' && currentAccountId) {
      // 可选：如需设置页数据刷新，可在此处加API
    }
  };

  return (
    <>
      <div className="main-layout">
        <Sidebar selected={sidebar} onSelect={handleSidebarSelect} />
        <div className="main-content">
          <div className="top-bar">
            <button onClick={() => setShowSelector(true)}>切换账号</button>
            <button onClick={() => setShowAccountModal(true)}>账号信息</button>
          </div>
          <div className="content-body">
            {renderContent()}
          </div>
        </div>
      </div>
      {showAccountModal && currentAccount && (
        <AccountInfoModal
          account={currentAccount}
          onClose={() => setShowAccountModal(false)}
          onExport={() => {
            safeCall(exportAccountData(currentAccount.id), '导出失败').then(res => {
              if (res) alert(res.message);
            });
          }}
        />
      )}
      {showSelector && (
        <AccountSelectorModal
          accounts={accounts}
          currentId={currentAccountId}
          onSelect={id => {
            setCurrentAccountId(id);
            setShowSelector(false);
          }}
          onClose={() => setShowSelector(false)}
        />
      )}
    </>
  );
};

export default MainPage; 